package org.jeecg.modules.strategy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.strategy.component.HomePageSpider;
import org.jeecg.modules.strategy.component.MetaSpider;
import org.jeecg.modules.strategy.mapper.AnalyticsMapper;
import org.jeecg.modules.strategy.mapper.WebsiteMetaMapper;
import org.jeecg.modules.strategy.model.entity.AnalyticsEntity;
import org.jeecg.modules.strategy.model.entity.AnalyticsProcessEntity;
import org.jeecg.modules.strategy.model.entity.AnalyticsResultEntity;
import org.jeecg.modules.strategy.model.entity.MetaEntity;
import org.jeecg.modules.strategy.model.query.AnalyticsProcessQuery;
import org.jeecg.modules.strategy.model.query.AnalyticsQuery;
import org.jeecg.modules.strategy.model.query.AnalyticsResultQuery;
import org.jeecg.modules.strategy.service.AnalyticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class AnalyticsServiceImpl extends ServiceImpl<AnalyticsMapper, AnalyticsEntity> implements AnalyticsService {
    private final HomePageSpider homePageSpider;
    private final MetaSpider metaSpider;
    @Resource
    private WebsiteMetaMapper websiteMetaMapper;

    @Autowired
    public AnalyticsServiceImpl(HomePageSpider homePageSpider, MetaSpider metaSpider) {
        this.homePageSpider = homePageSpider;
        this.metaSpider = metaSpider;
    }

    @Override
    public Result<String> startCollectMetaTask(AnalyticsQuery analytics) {
        String siteDomain = analytics.getUrl().replaceAll("https://", "").replace("http://", "").replace("/", "");
        LambdaQueryWrapper<AnalyticsEntity> analyticsEntityListLambdaQueryWrapper = new LambdaQueryWrapper<>();
        analyticsEntityListLambdaQueryWrapper.eq(AnalyticsEntity::getSiteDomain, siteDomain)
                .eq(AnalyticsEntity::getIsDelete, "0");
        List<AnalyticsEntity> analyticsEntityList = this.list(analyticsEntityListLambdaQueryWrapper);
        if (!analyticsEntityList.isEmpty())
            return Result.error("该网站已存在分析任务");
        String homePageMetaContent = homePageSpider.startCollectHomePageMetaTask(analytics);
        if (homePageMetaContent.equals("error"))
            return Result.error("获取首页Meta任务启动失败");
        // String metaContent = metaSpider.startCollectMetaTask(analytics);
        // if (metaContent.equals("error"))
        //     return Result.error("获取Meta任务启动失败");
        LambdaQueryWrapper<MetaEntity> metaEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
        metaEntityLambdaQueryWrapper.eq(MetaEntity::getSiteDomain, siteDomain)
                .ne(MetaEntity::getArticleTitle, "")
                .isNotNull(MetaEntity::getArticleTitle)
                .eq(MetaEntity::getIsDelete, "0");
        Long total = websiteMetaMapper.selectCount(metaEntityLambdaQueryWrapper);
        LambdaQueryWrapper<AnalyticsEntity> analyticsEntityGetLambdaQueryWrapper = new LambdaQueryWrapper<>();
        analyticsEntityGetLambdaQueryWrapper.eq(AnalyticsEntity::getSiteDomain, siteDomain)
                .eq(AnalyticsEntity::getIsDelete, "0");
        AnalyticsEntity analyticsEntity = this.getOne(analyticsEntityGetLambdaQueryWrapper);
        if (total > 0 && !StringUtils.isEmpty(analyticsEntity.getSiteDomain()) && !StringUtils.isEmpty(analyticsEntity.getSiteName()) && !StringUtils.isEmpty(analyticsEntity.getSiteIdCode())){
            analyticsEntity.setStatus(1);
            analyticsEntity.setTotal(Math.toIntExact(total));
            analyticsEntity.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            this.updateById(analyticsEntity);
        } else {
            this.removeById(analyticsEntity);
            return Result.error("网站分析失败");
        }
        return Result.OK("网站分析已完成");
    }

    @Override
    public List<AnalyticsEntity> listAnalyticsTask() {
        if (this.count() > 0) {
            LambdaQueryWrapper<AnalyticsEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(AnalyticsEntity::getIsDelete, "0")
                    .ne(AnalyticsEntity::getSiteDomain, "")
                    .ne(AnalyticsEntity::getSiteName, "")
                    .ne(AnalyticsEntity::getSiteIdCode, "");
            return this.list(queryWrapper);
        }
        return null;
    }

    @Override
    public AnalyticsProcessEntity getAnalyticsProcess(AnalyticsProcessQuery analyticsProcessQuery) {
        AnalyticsEntity analytics = this.getById(analyticsProcessQuery.getId());
        if (Objects.equals(analyticsProcessQuery.getSiteDomain().replaceAll(" ", ""), analytics.getSiteDomain().replaceAll(" ", ""))
                && !StringUtils.isEmpty(analytics.getSiteName())
                && !StringUtils.isEmpty(analytics.getSiteIdCode())) {
            LambdaQueryWrapper<MetaEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(MetaEntity::getSiteDomain, analytics.getSiteDomain())
                    .eq(MetaEntity::getSiteName, analytics.getSiteName())
                    .eq(MetaEntity::getSiteIdCode, analytics.getSiteIdCode())
                    .eq(MetaEntity::getIsDelete, "0")
                    .ne(MetaEntity::getArticleTitle, "");
            Long total = websiteMetaMapper.selectCount(queryWrapper);
            String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            LocalDateTime endTime = LocalDateTime.parse(currentTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            LocalDateTime startTime = LocalDateTime.parse(analytics.getUpdateTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            long betweenTime = ChronoUnit.SECONDS.between(startTime, endTime);
            AnalyticsProcessEntity analyticsProcessEntity = new AnalyticsProcessEntity();
            analyticsProcessEntity.setTotal(Math.toIntExact(total));
            analyticsProcessEntity.setTimeConsumed(Math.toIntExact(betweenTime));
            if (analyticsProcessEntity.getTimeConsumed() > 0 && analyticsProcessEntity.getTotal() > 0)
                return analyticsProcessEntity;
        }
        return null;
    }

    @Override
    public List<AnalyticsResultEntity> getAnalyticsResult(AnalyticsResultQuery analyticsResultQuery) {
        AnalyticsEntity analytics = this.getById(analyticsResultQuery.getId());
        if (Objects.equals(analyticsResultQuery.getSiteDomain().replaceAll(" ", ""), analytics.getSiteDomain().replaceAll(" ", ""))
                && !StringUtils.isEmpty(analytics.getSiteName())
                && !StringUtils.isEmpty(analytics.getSiteIdCode())) {
            List<AnalyticsResultEntity> analyticsResult = websiteMetaMapper.getGroupBy(analytics);
            if (!analyticsResult.isEmpty()) {
                return analyticsResult;
            }
        }
        return null;
    }
}
